package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.*;
import com.winning.pmph.service.*;
import com.winning.pmph.utils.PMPHAppUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Api(value = "知识资源管理/投稿管理")
@RestController
@RequestMapping("/pmph/action/activity")
public class ActivityCtrl {
    @Resource
    TaskService taskService;
    @Resource
    private ActivityService activityService;
    @Resource
    private KnowledgeLibService knowledgeLibService;
    @Resource
    private ActivityItemService activityItemService;
    @Resource
    private UserService userService;

    @ApiOperation(value = "selectTableData", notes = "全部活动查询列表")
    @GetMapping("selectTableData")
    public Page<Activity> selectTableData(String name, String status, String knowledgeLibId,
                                          String createdBy, Integer currentPage, Integer pageSize) {
        if (StringUtils.equals(status, "all")) {
            User userByUserName = userService.getUserName(createdBy);
            if (userByUserName != null) {
                createdBy = userByUserName.getUserName();
            }
        } else {
            createdBy = PMPHAppUtil.getCurrentUserEnName();
        }
        Page<Activity> activityPage = activityService
                .lambdaQuery()
                .like(StringUtils.isNotEmpty(name), Activity::getName, name)
                .eq(StringUtils.isNotEmpty(knowledgeLibId), Activity::getKnowledgeLibId, knowledgeLibId)
                .like(StringUtils.isNotEmpty(createdBy), Activity::getCreatedBy, createdBy)
                .orderByDesc(Activity::getUpdatedTime)
                .orderByAsc(Activity::getId)
                .page(new Page<>(currentPage, pageSize));
        for (Activity activity : activityPage.getRecords()) {
            if (StringUtils.isNotBlank(activity.getKnowledgeLibId())) {
                KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(activity.getKnowledgeLibId());
                activity.setKnowledgeLibName(knowledgeLib.getName());
                List<ActivityItem> list = activityItemService.lambdaQuery().eq(ActivityItem::getActivityId, activity.getId()).eq(ActivityItem::getDeleted, ActivityItem.DELETED_NO).list();
                activity.setManuscriptNum(list.size());
            }
        }
        return activityPage;
    }

    @ApiOperation(value = "selectActivityItemTableData", notes = "我的活动查询列表")
    @GetMapping("selectActivityItemTableData")
    public Page<ActivityItem> selectActivityItemTableData(String id, String knowledgeLibId, String manuscriptName,
                                                          String taskName, String name, String radioStatus,
                                                          Integer currentPage, Integer pageSize) {
        int status = 0;
        if (StringUtils.equals(radioStatus, "distribution")) {
            status = ActivityItem.DISTRIBUTION;
        } else if (StringUtils.equals(radioStatus, "undistributed")) {
            status = ActivityItem.UNDISTRIBUTED;
        } else {
            status = ActivityItem.FAIL;
        }
        String taskId = "";
        if (StringUtils.isNotBlank(taskName)) {
            taskId = taskService.lambdaQuery().eq(Task::getName, taskName).one().getId();
        }
        Page<ActivityItem> activityItemPage = activityItemService
                .lambdaQuery()
                .eq(ActivityItem::getStatus, status)
                .like(StringUtils.isNotBlank(manuscriptName), ActivityItem::getManuscriptName, manuscriptName)
                .eq(StringUtils.isNotBlank(id), ActivityItem::getActivityId, id)
                .eq(ActivityItem::getDeleted, ActivityItem.DELETED_NO)
                .like(StringUtils.isNotEmpty(name), ActivityItem::getKnowledgeName, name)
                .eq(StringUtils.isNotEmpty(taskId), ActivityItem::getTaskId, taskId)
                .eq(StringUtils.isNotEmpty(knowledgeLibId), ActivityItem::getKnowledgeLibId, knowledgeLibId)
                .orderByDesc(ActivityItem::getUpdatedTime)
                .orderByAsc(ActivityItem::getId)
                .page(new Page<>(currentPage, pageSize));

        for (ActivityItem activityItem : activityItemPage.getRecords()) {
            KnowledgeLib knowledgeLib = knowledgeLibService.getBaseMapper().selectById(activityItem.getKnowledgeLibId());
            activityItem.setKnowledgeLibName(knowledgeLib.getName());
            if (StringUtils.equals(radioStatus, "distribution")) {
                Task task = taskService.getById(activityItem.getTaskId());
                activityItem.setTaskName(task.getName());
            }
        }
        return activityItemPage;
    }

    @ApiOperation(value = "updateUser", notes = "全部活动分配负责人接口")
    @PostMapping("updateUser")
    public void updateUser(String userName, String activityId) {
        activityService.update(Wrappers.lambdaUpdate(Activity.class)
                .set(Activity::getCreatedBy, userName)
                .eq(Activity::getId, activityId));
    }

    @ApiOperation(value = "saveTaskItemList", notes = "详情功能分配任务接口")
    @PostMapping("saveTaskItemList")
    public void saveTaskItemList(String editType, String selectedActivityIds,
                                 String taskId, String remark, String searchParams,
                                 String id) {
        JSONObject searchParamsObj = JSON.parseObject(searchParams);
        String username = PMPHAppUtil.getCurrentUserEnName();
        activityItemService.addTaskItemList(id, editType, selectedActivityIds, taskId, remark, searchParamsObj, username);
    }

    @ApiOperation(value = "selectItemTableData", notes = "word导入结果页面")
    @GetMapping("selectItemTableData")
    public Page<ActivityItem> selectItemTableData(String manuscriptName, Integer currentPage, Integer pageSize, String status, String updateTime, String taskId) {
        LambdaQueryWrapper<ActivityItem> activityItemLambdaQueryWrapper = Wrappers.lambdaQuery(ActivityItem.class).like(StringUtils.isNotBlank(manuscriptName), ActivityItem::getManuscriptName, manuscriptName)
                .eq(StringUtils.isNotBlank(status), ActivityItem::getStatus, status)
                .eq(StringUtils.isNotBlank(taskId), ActivityItem::getTaskId, taskId)
                .orderByDesc(ActivityItem::getUpdatedTime)
                .orderByAsc(ActivityItem::getId);
        if (StringUtils.isNotBlank(updateTime)) {
            activityItemLambdaQueryWrapper = activityItemLambdaQueryWrapper.ge(ActivityItem::getUpdatedTime, updateTime.split(",")[0].trim())
                    .le(ActivityItem::getUpdatedTime, updateTime.split(",")[1].trim());
        }
        return activityItemService.page(new Page<>(currentPage, pageSize), activityItemLambdaQueryWrapper);
    }

    @ApiOperation(value = "deleteItemById", notes = "根据ID删除word导入结果的某条稿件")
    @PostMapping("deleteItemById")
    public void deleteItemById(String id) {
        activityItemService.removeById(id);
    }

    @ApiOperation(value = "downloadManuscript", notes = "根据ID删除word导入结果的某条稿件")
    @GetMapping("downloadManuscript")
    public void downloadManuscript(String path, HttpServletResponse response) {
        String fileName = StringUtils.substringAfterLast(path, "/");
        ServletOutputStream outStream = null;
        try {
            InputStream input = new FileInputStream(new File(path));
            response.setContentType("application/docx;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            outStream = response.getOutputStream();
            int byteRead = 0;
            byte[] buffer = new byte[512];
            while ((byteRead = input.read(buffer)) != -1) {
                outStream.write(buffer, 0, byteRead);
            }
            input.close();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
